package com.example.administrator.text;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.text.Framgnet.PeripheryFragment;
import com.example.administrator.text.Framgnet.We1Fragment;
import com.example.administrator.text.Framgnet.WiFiFragment;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import data.SharedPreferencesUtils;
import entity.Home;
import util.AgentIp;
import util.BReceiverUtil.NetWorkstateReceiver;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import util.listComparator.HomeBotton;
import util.listComparator.HomeBoxTap;
import view.HomeStateLLayout;
import view.MorePopWindow;
import view.diaLogView.CouponDialog;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.UploadDialog;
/**
 * 首页
 */
public class HomeActivity extends BaseActivity implements HomeUtil.OnHomeUtilClickListener {
    public static final String mAction = "altair";
    private int mOrdinal;                                              //底部控件所对应的集合的序号
    private int mDataFrequency = 0;                                   //加载数据失败的次数
    private String mToken, mId,mFwq;
    private boolean mHomeActivityState;                            //是否被内存回收
    private int mNewsFrequency = 0;                               //消息的个数
    private boolean mJumdPull = true;                            //是否要显示显示提示
    private int mButtomSubscript = 0;                           //记录底部的点击事件

    /**
     * Fragment的TAG 用于解决app内存被回收之后导致的fragment重叠问题
     */
    private static final  String[] FRAGMENT_TAG = {"WiFi","DiTu","WoDe","BaoZan","FuLi"};
    private MorePopWindow mMorePopWindow;
    private IntentFilter mIntentFilter;
    private PeripheryFragment mPeripheryFragment;            //周边
    private We1Fragment mWe1Fragment;
    private WiFiFragment mWiFiFragment;
    private List<Home.BottomTabBarBean> mBottomTabBarBeen;  //首页底部的控件数据集合
    private List<Home.ComboBoxTapBarBean> mBoxTap;         //首页左上角的下拉框
    private Bundle mSavedInstanceState;                   //如果屏幕发生旋转，Activity发生重新启动 或者按home 键很久才返回 会从新加载activity和Fragment
    private NetWorkstateReceiver mNetWorkstateReceivern;
    private UploadDialog mUploadDialog;

    @Bind(R.id.linear_home_botton_f)
    LinearLayout mLinearLayout;               //底部父View
    @Bind(R.id.view_homestate5)
    HomeStateLLayout mHomeButton4;            //第5个
    @Bind(R.id.view_homestate4)
    HomeStateLLayout mHomeButton3;          //第4个
    @Bind(R.id.view_homestate3)
    HomeStateLLayout mHomeButton2;        //第三个
    @Bind(R.id.view_homestate2)
    HomeStateLLayout mHomeButton1;      //第二个
    @Bind(R.id.view_homestate1)
    HomeStateLLayout mHomeButton0;    //第一个
    @Bind(R.id.frame_home)
    FrameLayout mFrameLoayout;
    @Bind(R.id.iv_home_fail)
    ImageView mIVfail;  //加载失败时显示的图
    @Bind(R.id.activity_home_tv_news)      TextView mTextViewNews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mSavedInstanceState = savedInstanceState;
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        getSavedInstanceState(savedInstanceState);
        init();
        getWindow().setFormat(PixelFormat.TRANSLUCENT);  //解决嵌套高德地图 出现闪屏的情况
        String id = JPushInterface.getRegistrationID(this);
        LogUtil.eE("","................id........................."+id);

    }

    /**
     * 消息
     */
    @OnClick(R.id.activity_home_fl_news)
    void news(){
        mNewsFrequency = 0;
        setNews();
        JPushInterface.clearAllNotifications(this);
        JumpActivityUtils.getInstance().jumpApiCloud3(this,StringUtil.getStringUtilNew().getPhshContext(),mId);
        StringUtil.getStringUtilNew().clearPhshData(this,0);
    }

    /**
     * 扫一扫
     */
    @OnClick(R.id.activity_home_iv_scan)
    void scan(){
        JumpActivityUtils.getInstance().jumpZXing(this);
    }

    /**
     *
     *
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        }
        return true;
    }

    private void  init() {
        setOnClick();
        HomeUtil.getHemeUtilNew().getStatusBar(this, mFrameLoayout);
        Window window = this.getWindow();
        //window.setNavigationBarColor(getResources().getColor(colorResId));
        mId = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        mToken = (String) SharedPreferencesUtils.getParam(HomeActivity.this, HomeUtil.mTokenDB, "");
        if(mHomeActivityState){getData();}

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(mAction);
        mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(broadcastReceiver, mIntentFilter);

        if (mNetWorkstateReceivern == null) {
            mNetWorkstateReceivern = new NetWorkstateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetWorkstateReceivern,filter);

        String type = getIntent().getStringExtra("home");
        if(type !=null && !type.equals("map")){
            HomeUtil.getHemeUtilNew().setLocation(this);
        }

    }

    /**
     * SavedInstanceState 不为空的操作
     */
    private void getSavedInstanceState(Bundle savedInstanceState){
        if(savedInstanceState != null){
            LogUtil.eE("",".............getSavedInstanceState.............1");
            mHomeActivityState = false;
            mWiFiFragment = (WiFiFragment)getFragmentManager().findFragmentByTag(FRAGMENT_TAG[1]);
            mWe1Fragment = (We1Fragment)getFragmentManager().findFragmentByTag(FRAGMENT_TAG[2]);
            mPeripheryFragment = (PeripheryFragment)getFragmentManager().findFragmentByTag(FRAGMENT_TAG[3]);

            if (mWiFiFragment != null) {
                getFragmentManager().beginTransaction().hide(mWiFiFragment).commitAllowingStateLoss();
            }
            if (mWe1Fragment != null) {
                getFragmentManager().beginTransaction().hide(mWe1Fragment).commitAllowingStateLoss();
            }
            if (mPeripheryFragment != null) {
                getFragmentManager().beginTransaction().hide(mPeripheryFragment).commitAllowingStateLoss();
            }
            updateAppState(0);
            SharedPreferencesUtils.setParam(this,HomeUtil.AppAgainState,true);
        }else{
            SharedPreferencesUtils.setParam(this,HomeUtil.AppAgainState,false);
            mHomeActivityState = true;
            LogUtil.eE("",".............getSavedInstanceState.............2");
        }
    }

    /**
     * 创建一个动态广播  13600160777
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String string = intent.getStringExtra("wifi");
            if (string != null && !string.equals("")) {
                LogUtil.eE("string", "进来....."+string);
                if (string.equals("wifiok")) {
                    if(MyApplication.getApp().getSiteAreaid() == 2){
                        SharedPreferencesUtils.setParam(HomeActivity.this,HomeUtil.appNetWorkstate,true);
                    }else {
                        SharedPreferencesUtils.setParam(HomeActivity.this,HomeUtil.appNetWorkstate,true);
                    }
                    if(intent.getStringExtra("networking") != null && !intent.getStringExtra("networking").equals("")){
                    }

                }else if(string.equals("wifl_view")){
                   if(mWiFiFragment !=null){
                    mWiFiFragment.wifiView(1);
                   }
                    if(mWe1Fragment !=null){
                        mWe1Fragment.setView();
                    }
                }else if(string.equals("updata_coupon")){
                    if(MyApplication.getApp().getSiteAreaid() != 1 && MyApplication.getApp().getSiteAreaid() != 2 ){
                        getCoupon();
                    }
                }else if(string.equals("jPush_context")){
                  String jPush_context = intent.getStringExtra("jPush_context");
                  if(jPush_context.equals("show")){
                      processInformation();
                  }else if(jPush_context.equals("ok")){
                      mJumdPull = false;
                  }else {
                      mNewsFrequency = 0;
                      setNews();
                  }
                }else if(string.equals("APICloud4")){
                    String msg = intent.getStringExtra("msg");
                    apiCloudOnClick(msg);
                }else if(string.equals("ZXing")){
                    JumpActivityUtils.getInstance().jumpZXing(HomeActivity.this);
                }else if(string.equals("finish")){
                    finish();
                }else if(string.equals("fuliOnClick")){
                    //getRadioGroupOrder("福利");
                    fuliOnClick();
                }
            }
        }
    };

    /**
     *处理apiCloud 的事件
     */
    private void apiCloudOnClick(String msg){
         if(msg.equals("keyback")){
             moveTaskToBack(true);
         }else {
             int i =  Integer.parseInt(msg);
             if( i < mBottomTabBarBeen.size() ){
                     LogUtil.eE("","........i..........."+i);
                     switch (i){
                         case 0:
                             mHomeButton0.setPerformOnClick();
                             break;
                         case 1:
                             mHomeButton1.setPerformOnClick();
                             break;
                         case 2:
                             mHomeButton2.setPerformOnClick();
                             break;
                         case 3:
                             mHomeButton3.setPerformOnClick();
                             break;
                         case 4:
                             mHomeButton4.setPerformOnClick();
                             break;
                     }
             }
         }
    }

    private void fuliOnClick(){
        for (int i = 0; i < mBottomTabBarBeen.size() ; i++) {
                 if(mBottomTabBarBeen.get(i).getType().equals("fuli")){
                     switch (i){
                         case 1:
                             mHomeButton1.setPerformOnClick();
                             break;
                         case 2:
                             mHomeButton2.setPerformOnClick();
                             break;
                         case 3:
                             mHomeButton3.setPerformOnClick();
                             break;
                         case 0:
                             mHomeButton0.setPerformOnClick();
                             break;
                         case 4:
                             mHomeButton4.setPerformOnClick();
                             break;
                     }
                 }
        }
    }

    /**
     * 处理信息
     */
    private void processInformation(){
        HashMap<String, Object> map = new HashMap<>();
        EventBus.getDefault().post(StringUtil.getStringUtilNew().getPullLast());
        mNewsFrequency++;
        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(mJumdPull){
                    setNews();
                }else {
                    mNewsFrequency--;
                    mJumdPull = true;
                    StringUtil.getStringUtilNew().clearPhshData(HomeActivity.this,1);
                }
            }
        },500);
    }

    private void setNews(){
        if(mNewsFrequency == 0){
            mTextViewNews.setVisibility(View.GONE);
        }else {
            mTextViewNews.setVisibility(View.VISIBLE);
            mTextViewNews.setText(mNewsFrequency+"");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mMorePopWindow != null) {
            mMorePopWindow.dismiss();
        }

        unregisterReceiver(broadcastReceiver);

        unregisterReceiver(mNetWorkstateReceivern);
        if(mWiFiFragment != null){
            mWiFiFragment.onDetach();
        }

    }

    /**
     * wifi页
     */
    private void wifiOnClick(){
        LogUtil.eE("","........wifiOnClick..........");
            if (mWiFiFragment == null) {
                LogUtil.eE("","........wifiOnClick..........==null");
                mWiFiFragment = WiFiFragment.newInstance();
                getFragmentManager().beginTransaction().add(R.id.framelayout_home, mWiFiFragment,FRAGMENT_TAG[1]).commitAllowingStateLoss();
            } else {
                getFragmentManager().beginTransaction().show(mWiFiFragment).commitAllowingStateLoss();
            }

            if (mPeripheryFragment != null) {
                getFragmentManager().beginTransaction().hide(mPeripheryFragment).commitAllowingStateLoss();
            }

            if (mWe1Fragment != null) {
                getFragmentManager().beginTransaction().hide(mWe1Fragment).commitAllowingStateLoss();
            }
    }

    /**
     * 周边
     */
    private void periphery(){

            if(mPeripheryFragment == null){
                mPeripheryFragment = new PeripheryFragment();
                getFragmentManager().beginTransaction().add(R.id.framelayout_home, mPeripheryFragment,FRAGMENT_TAG[3]).commitAllowingStateLoss();
            }else {
                getFragmentManager().beginTransaction().show(mPeripheryFragment).commitAllowingStateLoss();
            }

            if(mWiFiFragment !=null){
                getFragmentManager().beginTransaction().hide(mWiFiFragment).commitAllowingStateLoss();
            }

            if (mWe1Fragment != null) {
                getFragmentManager().beginTransaction().hide(mWe1Fragment).commitAllowingStateLoss();
            }
    }

    /**
     * 我的页
     */
    private void we1OnClick(){
        LogUtil.eE("","........we1OnClick..........");
            if (mWe1Fragment == null) {
                LogUtil.eE("","........we1OnClick..........==null");
                mWe1Fragment = We1Fragment.newInstance();
                getFragmentManager().beginTransaction().add(R.id.framelayout_home, mWe1Fragment,FRAGMENT_TAG[2]).commitAllowingStateLoss();
            } else {
                getFragmentManager().beginTransaction().show(mWe1Fragment).commitAllowingStateLoss();
                mWe1Fragment.getWhitelis();
                mWe1Fragment.showBalance();
            }

            if (mPeripheryFragment != null) {
                getFragmentManager().beginTransaction().hide(mPeripheryFragment).commitAllowingStateLoss();
            }

            if(mWiFiFragment !=null){
                getFragmentManager().beginTransaction().hide(mWiFiFragment).commitAllowingStateLoss();
            }
    }

    /**
     * 收取该页面的数据
     */
    private void getData() {
        mMap = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        if(mBottomTabBarBeen !=null){mBottomTabBarBeen.clear();}
        if(mBoxTap !=null){mBoxTap.clear();}
        mMap.put("userid",id);
        mMap.put("token",mToken);
        mMap.put("areaid",MyApplication.getApp().getSiteAreaid());
        mMap.put("ver",getInformation.getNewGetInformation(this).getVersion());
        mMap.put("vertype",1);
        mMap.put("appType",1);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUrl_getlinks,stringJson,mToken,id,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,id, Url.mStirngUrl_getlinks,stirngSign,time);
        LogUtil.eE("", "areaid" + MyApplication.getApp().getSiteAreaid() + "token   " + mToken + "userid" + id);
        getLogger().info("getData*()---->fwq--" + MyApplication.getApp().getFWQString() + "stringJson--" + stringJson+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.getApp().getFWQString(),1,map1, new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                LogUtil.eE("", response);
                try {
                    Gson gson = new Gson();
                    if (response.length() < 80) {
                        getLogger().info("getData*()---->onSuccess()--String--" + response);
                        mIVfail.setVisibility(View.VISIBLE);
                        mIVfail.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mIVfail.setVisibility(View.GONE);
                                getData();
                            }
                        });
                        Toast.makeText(HomeActivity.this, getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                    }else {
                        getLogger().info("getData*()---->onSuccess()--String--" + response);
                        mIVfail.setVisibility(View.GONE);
                        mBottomTabBarBeen = new ArrayList<>();
                        mBoxTap = new ArrayList<>();
                        Home home = gson.fromJson(response, Home.class);
                        if(home !=null){
                            if (home.getCode() == 1) {
                                if(home.getBottomTabBar() !=null){
                                    mBottomTabBarBeen = home.getBottomTabBar();
                                    mBoxTap = home.getComboBoxTapBar();
                                    Collections.sort(mBottomTabBarBeen, new HomeBotton());//排序
                                    if(mUploadDialog !=null){mUploadDialog.dismiss();}
                                    setHomeBottonn();
                                    setHomeTop();
                                    Collections.sort(mBoxTap,new HomeBoxTap());//排序
                                    if(MyApplication.getApp().getSiteAreaid() !=1 && MyApplication.getApp().getSiteAreaid() !=2){
                                        HomeUtil.getHemeUtilNew().getVip(HomeActivity.this,mId,mToken);
                                    }

                                    if(home.getNoticeArea() != null && home.getNoticeId() != null && home.getNoticeUrl() != null){
                                        setNotice(home.getNoticeArea(),home.getNoticeId(),home.getNoticeUrl());
                                    }
                                }else {
                                    mIVfail.setVisibility(View.VISIBLE);
                                    mIVfail.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            mIVfail.setVisibility(View.GONE);
                                            getData();
                                        }
                                    });
                                    Toast.makeText(HomeActivity.this, getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                                }
                                getPullData();
                                setPullNews();
                            } else if (home.getCode() == -1) {
                                Toast.makeText(HomeActivity.this,getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                            } else if (home.getCode() == -2) {
                                CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(HomeActivity.this);
                                crowdRetunDialog.show();
                            }else {
                                Toast.makeText(HomeActivity.this,getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            mIVfail.setVisibility(View.VISIBLE);
                            mIVfail.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mIVfail.setVisibility(View.GONE);
                                    getData();
                                }
                            });
                            Toast.makeText(HomeActivity.this, getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                        }
                    }
                }catch (Exception e){
                    mIVfail.setVisibility(View.VISIBLE);
                    mIVfail.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mIVfail.setVisibility(View.GONE);
                            getData();
                        }
                    });
                    Toast.makeText(HomeActivity.this, getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                if(mDataFrequency == 0){
                    mDataFrequency++;
                    updateAppState(0);
                }else {
                    if(mUploadDialog !=null){mUploadDialog.dismiss();}
                    if(!Url.getUrlNew().isNetWorkstateState()){
                        Url.getUrlNew().setNetWorkstateState(true);
                        mIVfail.setVisibility(View.VISIBLE);
                        mIVfail.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDataFrequency = 0;
                                mIVfail.setVisibility(View.GONE);
                                HomeUtil.getHemeUtilNew().saveCombo(HomeActivity.this,0,null);
                                getData();
                            }
                        });
                        StringUtil.getStringUtilNew().getExceptionCode(HomeActivity.this, error.toString());
                    }
                }
            }
        });
    }

    /**
     * 读取 本地推送数据
     */
    private void setPullNews() {
        List<String> list = (List<String>) SharedPreferencesUtils.getParam(this,"Pull_list","list");
        LogUtil.eE("",".................setPullNews............"+list);
        if(list != null && list.size()>0){
            mNewsFrequency = list.size();
            setNews();
            StringUtil.getStringUtilNew().setPhshContext(this,"",1,list);
        }
    }

    /**
     *查看系统公告 看是否需要展示
     */
    public void setNotice(int[] strings,String noticeId,String noticeUrl){
        for (int i = 0; i <strings.length ; i++) {
             if(MyApplication.getApp().getSiteAreaid() == strings[i]){
                 LogUtil.eE("","...setNotice....................."+noticeId);
              if(!SharedPreferencesUtils.getParam(this,HomeUtil.mAppNoticeNoticeId,"").equals(noticeId)){
                  SharedPreferencesUtils.setParam(this,HomeUtil.mAppNoticeNoticeId,noticeId);
                  JumpActivityUtils.getInstance().jumpWebView(this,noticeUrl,"公告");
              }
             }
        }
    }

    /**
     * view事件的处理
     */
    private void setOnClick() {
        mHomeButton0.setViewOnClickListener(new HomeStateLLayout.ViewOnClickListener() {
            @Override
            public void onViewClick(String string) {
                getRadioGroupOrder(string);
            }
        });

        mHomeButton1.setViewOnClickListener(new HomeStateLLayout.ViewOnClickListener() {
            @Override
            public void onViewClick(String string) {
                getRadioGroupOrder(string);
            }
        });

        mHomeButton2.setViewOnClickListener(new HomeStateLLayout.ViewOnClickListener() {
            @Override
            public void onViewClick(String string) {
                getRadioGroupOrder(string);
            }
        });

        mHomeButton3.setViewOnClickListener(new HomeStateLLayout.ViewOnClickListener() {
            @Override
            public void onViewClick(String string) {
                getRadioGroupOrder(string);
            }
        });

        mHomeButton4.setViewOnClickListener(new HomeStateLLayout.ViewOnClickListener() {
            @Override
            public void onViewClick(String string) {
                getRadioGroupOrder(string);
            }
        });
    }


    /**
     * 获取RB所对应序号 在配备所对应的事件
     *
     * @param rbName 控件的Name
     */
    private void getRadioGroupOrder(String rbName) {
        LogUtil.eE("", rbName);
       if (getOrdinal(rbName).equals("wifi")) {
                wifiOnClick();
                setViewhide();
            mButtomSubscript = 0;
            EventBus.getDefault().post("Close");
        }else if (getOrdinal(rbName).equals("zhoubian")) {
                periphery();
                setViewhide();
            mButtomSubscript = 0;
            EventBus.getDefault().post("Close");
        }else if (getOrdinal(rbName).equals("fuli")) {
               // getShouYeOnClick();
            if(mButtomSubscript == 0 || mButtomSubscript == 2){
                mButtomSubscript = 1;
                EventBus.getDefault().post("Close");
                JumpActivityUtils.getInstance().jumpApiCloud4(this,getInformation.getNewGetInformation(this).px2dip(mFrameLoayout.getMeasuredHeight()),mBottomTabBarBeen.size(),1,mId,mToken);
                setViewhide();
            }


        }else if (getOrdinal(rbName).equals("wode")) {
            we1OnClick();
            setViewhide();
            mButtomSubscript = 0;
            EventBus.getDefault().post("Close");
        }else if (getOrdinal(rbName).equals("ditu")) {
            //mapOnClick();
            if(mButtomSubscript == 0 || mButtomSubscript == 1) {
                mButtomSubscript = 2;
                JumpActivityUtils.getInstance().jumpApiCloud4(this, getInformation.getNewGetInformation(this).px2dip(mFrameLoayout.getMeasuredHeight()), mBottomTabBarBeen.size(), 2, mId, mToken);
                setViewhide();
                EventBus.getDefault().post("Close");
            }
        }
    }

    /**
     * 找到下面的序号
     */
    private String getOrdinal(String string) {
        if (mBottomTabBarBeen != null && mBottomTabBarBeen.size() != 0) {
            for (int i = 0; i < mBottomTabBarBeen.size(); i++) {
                if (string.equals(mBottomTabBarBeen.get(i).getTitle())) {
                    mOrdinal = i;
                    return mBottomTabBarBeen.get(i).getType();
                }
            }
        }
        return "";
    }

    /**
     * 当你点击View时，其他的View许变成false状态
     */
    private void setViewhide() {

        if (mOrdinal == 0) {
            mHomeButton1.setViewState();
            mHomeButton2.setViewState();
            mHomeButton3.setViewState();
            mHomeButton4.setViewState();
            mHomeButton1.setFalseView();
            mHomeButton2.setFalseView();
            mHomeButton3.setFalseView();
            mHomeButton4.setFalseView();
        } else if (mOrdinal == 1) {
            mHomeButton0.setViewState();
            mHomeButton2.setViewState();
            mHomeButton3.setViewState();
            mHomeButton4.setViewState();
            mHomeButton0.setFalseView();
            mHomeButton2.setFalseView();
            mHomeButton3.setFalseView();
            mHomeButton4.setFalseView();
        } else if (mOrdinal == 2) {
            mHomeButton1.setViewState();
            mHomeButton0.setViewState();
            mHomeButton3.setViewState();
            mHomeButton4.setViewState();
            mHomeButton1.setFalseView();
            mHomeButton0.setFalseView();
            mHomeButton3.setFalseView();
            mHomeButton4.setFalseView();
        } else if (mOrdinal == 3) {
            mHomeButton1.setViewState();
            mHomeButton2.setViewState();
            mHomeButton0.setViewState();
            mHomeButton4.setViewState();
            mHomeButton1.setFalseView();
            mHomeButton2.setFalseView();
            mHomeButton0.setFalseView();
            mHomeButton4.setFalseView();
        } else if (mOrdinal == 4) {
            mHomeButton1.setViewState();
            mHomeButton2.setViewState();
            mHomeButton3.setViewState();
            mHomeButton0.setViewState();
            mHomeButton1.setFalseView();
            mHomeButton2.setFalseView();
            mHomeButton3.setFalseView();
            mHomeButton0.setFalseView();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LogUtil.eE("","............onSaveInstanceState..............");
    }

    /**
     * 底部的数据显示
     */
    private void setHomeBottonn() {

        for (int i = 0; i < mBottomTabBarBeen.size(); i++) {
            if (i == 0) {
                mHomeButton0.setTextStirng(mBottomTabBarBeen.get(i).getTitle());
                setHomeButtonBackground(mHomeButton0, mBottomTabBarBeen.get(i).getType());
                mHomeButton0.setImageBackground(mBottomTabBarBeen.get(i).getIcon(), mBottomTabBarBeen.get(i).getSelectedIcon());
            } else if (i == 1) {
                mHomeButton1.setTextStirng(mBottomTabBarBeen.get(i).getTitle());
                setHomeButtonBackground(mHomeButton1, mBottomTabBarBeen.get(i).getType());
                mHomeButton1.setImageBackground(mBottomTabBarBeen.get(i).getIcon(), mBottomTabBarBeen.get(i).getSelectedIcon());
            } else if (i == 2) {
                mHomeButton2.setTextStirng(mBottomTabBarBeen.get(i).getTitle());
                setHomeButtonBackground(mHomeButton2, mBottomTabBarBeen.get(i).getType());
                mHomeButton2.setImageBackground(mBottomTabBarBeen.get(i).getIcon(), mBottomTabBarBeen.get(i).getSelectedIcon());
            } else if (i == 3) {
                mHomeButton3.setTextStirng(mBottomTabBarBeen.get(i).getTitle());
                setHomeButtonBackground(mHomeButton3, mBottomTabBarBeen.get(i).getType());
                mHomeButton3.setImageBackground(mBottomTabBarBeen.get(i).getIcon(), mBottomTabBarBeen.get(i).getSelectedIcon());
            } else if (i == 4) {
                mHomeButton4.setTextStirng(mBottomTabBarBeen.get(i).getTitle());
                setHomeButtonBackground(mHomeButton4, mBottomTabBarBeen.get(i).getType());
                mHomeButton4.setImageBackground(mBottomTabBarBeen.get(i).getIcon(), mBottomTabBarBeen.get(i).getSelectedIcon());
            }
        }
        perform();

        if (mBottomTabBarBeen.size() == 3) {
            mHomeButton3.setVisibility(View.GONE);
            mHomeButton4.setVisibility(View.GONE);
            mHomeButton0.setVisibility(View.VISIBLE);
            mHomeButton1.setVisibility(View.VISIBLE);
            mHomeButton2.setVisibility(View.VISIBLE);
        }

        if (mBottomTabBarBeen.size() == 4) {
            mHomeButton4.setVisibility(View.GONE);
            mHomeButton0.setVisibility(View.VISIBLE);
            mHomeButton1.setVisibility(View.VISIBLE);
            mHomeButton2.setVisibility(View.VISIBLE);
            mHomeButton3.setVisibility(View.VISIBLE);
        }

        if (mBottomTabBarBeen.size() == 5) {
            mHomeButton4.setVisibility(View.VISIBLE);
            mHomeButton0.setVisibility(View.VISIBLE);
            mHomeButton1.setVisibility(View.VISIBLE);
            mHomeButton2.setVisibility(View.VISIBLE);
            mHomeButton3.setVisibility(View.VISIBLE);
        }

        if (mBottomTabBarBeen.size() == 2) {
            mHomeButton2.setVisibility(View.GONE);
            mHomeButton3.setVisibility(View.GONE);
            mHomeButton4.setVisibility(View.GONE);
            mHomeButton0.setVisibility(View.VISIBLE);
            mHomeButton1.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 寻找首页的下标,进行模拟点击
     */
    private void perform() {
            mHomeButton0.setPerformOnClick();
    }

    /**
     * 顶部的数据显示
     */
    private void setHomeTop() {

    }

    /**
     * 设置默认的背景图片
     *
     * @param type 位置的标识
     */
    private void setHomeButtonBackground(HomeStateLLayout honestate, String type) {
        LogUtil.eE("","setHomeButtonBackground"+type);
        if (type.equals("fuli")) {
            honestate.setImageBackgroundId(R.mipmap.welfare, R.mipmap.welfare2);
        } else if (type.equals("baozhang")) {
            honestate.setImageBackgroundId(R.mipmap.fault_true, R.mipmap.fault_false);
        } else if (type.equals("wode")) {
            honestate.setImageBackgroundId(R.mipmap.my, R.mipmap.my2);
        } else if (type.equals("wifi")) {
            honestate.setImageBackgroundId(R.mipmap.newfi_true, R.mipmap.newfi_false);
        }else if (type.equals("zhoubian")) {
            honestate.setImageBackgroundId(R.mipmap.periphery1, R.mipmap.periphery2);
        }else if (type.equals("zhuye")) {
            honestate.setImageBackgroundId(R.mipmap.main_true, R.mipmap.main_false);
        }else if (type.equals("gerenzhongxin")) {
            honestate.setImageBackgroundId(R.mipmap.we_true, R.mipmap.we_false);
        }else if(type.equals("ditu")){
            honestate.setImageBackgroundId(R.mipmap.home_map1, R.mipmap.home_map2);
        }
    }

    /**
     * 未登录时 调用的方法
     */
    private void setReplyState() {
        if (mOrdinal == 0) {
            mHomeButton0.getReplyState();
        } else if (mOrdinal == 1) {
            mHomeButton1.getReplyState();
        } else if (mOrdinal == 2) {
            mHomeButton2.getReplyState();
        } else if (mOrdinal == 3) {
            mHomeButton3.getReplyState();
        } else if (mOrdinal == 4) {
            mHomeButton4.getReplyState();
        }
    }

    @Override
    public void onItemClick(String type) {
        LogUtil.eE("TYPE", type);
        if (!type.equals("")) {
            if (type.equals(HomeUtil.XIALA)) {
                if (mMorePopWindow == null) {
                    mMorePopWindow = new MorePopWindow(this, mBoxTap);
                } else {
                }
            } else {
                switch (Integer.parseInt(type)) {
                    case 0:
                        mHomeButton0.setPerformOnClick();
                        break;
                    case 1:
                        mHomeButton1.setPerformOnClick();
                        break;
                    case 2:
                        mHomeButton2.setPerformOnClick();
                        break;
                    case 3:
                        mHomeButton3.setPerformOnClick();
                        break;
                    case 4:
                        mHomeButton4.setPerformOnClick();
                        break;
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode,data);
        LogUtil.eE("","onActivityResult......1");
        switch (requestCode) {
            case RESULT_FIRST_USER:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    String string = bundle.getString("result");
                    getLogger().debug("onActivityResult---->扫码--->成功" + string);
                    HomeUtil.getHemeUtilNew().getSessionId(this, string, mId, mToken);
                }
                break;
        }
    }

    /**
     * 查询 优惠券
     */
    private void getCoupon(){
        HomeUtil.getHemeUtilNew().getCoupon(this,new HomeUtil.OnCouponClickListener() {
            @Override
            public void onItemClick(String string) {
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    getLogger().info("getCoupon()--onSuccess().."+string);
                    int code = jsonObject.getInt("code");
                    if(code == 1){
                        JSONArray jsonArray = jsonObject.getJSONArray("ticket");
                        LogUtil.eE("","................getCoupon().."+jsonArray.length()+"");
                        if(jsonArray.length()>0 ){
                            CouponDialog couponDialog = new CouponDialog(HomeActivity.this,jsonArray);
                            couponDialog.show();
                        }
                    }else if(code == -2){
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(HomeActivity.this);
                        crowdRetunDialog.show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 当在后台运行时间比较久了  会出现状态出错的情况
     */
    public void updateAppState(int type){
        if(mUploadDialog == null){
            mUploadDialog = new UploadDialog(this,"加载中");
            mUploadDialog.show();
        }else {
            mUploadDialog.show();
        }
        HashMap<String,Object> json = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        if(id.equals("")){
            json.put("userid",0);
        }else {json.put("userid",id);}
        json.put("apMac",getInformation.getNewGetInformation(this).getWiFiMac());
        json.put("apName",getInformation.getNewGetInformation(this).getWIFIName());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(json); //参数包
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,mToken,mId,time);
        Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.mStirngVersion_isAlive,stirngSign,time);
        if(type == 0){mFwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");}
        getLogger().info("updateAppState()--在后台运行时间比较长了更新一些状态->"+"fwq--"+mFwq);
        GreenTreeNetworkUtil.getInstance().doPost(this,mFwq,1500,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        getLogger().info("updateAppState()--->onSuccess--->"+"String--"+response);
                                if(jsonObject.getInt("siteAreaid") != 0){
                                    SharedPreferencesUtils.setParam(HomeActivity.this, HomeUtil.mFWQ,mFwq);
                                }
                        MyApplication.getApp().setSiteAreaid(jsonObject.getInt("siteAreaid"));
                        MyApplication.getApp().setFWQString(mFwq);
                        HomeUtil.getHemeUtilNew().saveCombo(HomeActivity.this,0,new HomeUtil.OnAppSaveComboClickListener() {
                            @Override
                            public void onItemClick(boolean state) {
                                      if(state){
                                          getData();
                                      }else {
                                          mUploadDialog.dismiss();
                                          mIVfail.setVisibility(View.VISIBLE);
                                          mIVfail.setOnClickListener(new View.OnClickListener() {
                                              @Override
                                              public void onClick(View v) {
                                                  getData();
                                                  mIVfail.setVisibility(View.GONE);
                                              }
                                          });
                                      }
                            }
                        });

                    }else if (jsonObject.getInt("code") == -1) {
                        mUploadDialog.dismiss();
                        Toast.makeText(HomeActivity.this,getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                    } else if (jsonObject.getInt("code") == -2) {
                        mUploadDialog.dismiss();
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(HomeActivity.this);
                        crowdRetunDialog.show();
                    }else {
                        mUploadDialog.dismiss();
                        Toast.makeText(HomeActivity.this,getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    updateAppStateNo(e.toString());
                }
            }

            @Override public void onFailure(Throwable error) {
               updateAppStateNo(error.toString());
            }
        });
    }

    private void updateAppStateNo(String error){
        getLogger().info("updateAppState-->onFailure()--->"+"Throwable--"+error);
        AgentIp.newInstance(HomeActivity.this).getIp(new AgentIp.OnAgentIpItemClickListener() {
            @Override
            public void onItemClick(String fwq) {
                getLogger().info("updateAppState-->onItemClick()--->"+"String--"+fwq);
                if(fwq.equals("没有查到")){
                    mUploadDialog.dismiss();
                    finish();
                    Intent in = new Intent(HomeActivity.this,WelComeActvity.class);
                    startActivity(in);
                }else {
                    mFwq = fwq;
                    updateAppState(1);
                }
            }
        });
    }

    /**
     * 拿去推送数据
     */
    public void getPullData(){
        String ip = StringUtil.getStringUtilNew().uploadHead(MyApplication.getApp().getFWQString());
        String pushIden = (String)SharedPreferencesUtils.getParam(this,HomeUtil.AppAltairPushIden,"");
        String timestamp = StringUtil.getStringUtilNew().getTimeCurrent()+"";
        Map<String,String> map = new HashMap<>();
        map.put("timestamp",timestamp);
        map.put("secretKey","messageService-Yh82922868~");
        map.put("noticeIden","");
        map.put("device","1");
        map.put("tabs",pushIden+","+mId);
        map.put("alias","");
        String sign = StringUtil.getStringUtilNew().getPushSign(map);
        Map<String,Object> map1 = new HashMap<>();
        map1.put("timestamp",timestamp);
        map1.put("sign",sign);
        map1.put("noticeIden","");
        map1.put("device","1");
        map1.put("tabs",pushIden+","+mId);
        map1.put("alias","");
        LogUtil.eE("pull","timestamp.."+timestamp+"..tabs.."+pushIden+","+mId+"...sign....."+sign+"...ip..."+ip+Url.getUrlNew().getPullData);
        GreenTreeNetworkUtil.getInstance().doPost(this,ip+Url.getUrlNew().getPullData,1,map1,new RequestDataCallback(){
            @Override
            public void onSuccess(String response) {
               LogUtil.eE("","............getPullData....."+response);
            }

            @Override
            public void onFailure(Throwable error) {
                LogUtil.eE("","............getPullData....."+error);
            }
        });
    }
}
